#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN DATA ABSTRACTION LAYER version 1

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For commercial software, please obtain a commercial license from THN Solutions LLC.

  + For free software, this library is licensed under GPL version 3. A summary of GPLv3 is
    listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt included
	with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Using directives
using System;
using System.IO;
using System.Xml;
#endregion

namespace Thn.Data.Settings
{
    /// <summary>
    /// A simple helper class for loading data configuration from xml file
    /// </summary>
    public class DataConfigurator
    {
        #region Load
        #region Load default file
        /// <summary>
        /// Load data configuration from file "Data.config". This file is expected to be in the same folder as the main program
        /// </summary>
        /// <returns>The database object to use</returns>
        public IDatabase Load()
        {
            return Load("Data.config", "");
        }
        #endregion      

        #region Load from file
        /// <summary>
        /// Load data configurations from an xml file
        /// </summary>
        /// <param name="name">Name of the database. A configuration file can have multiple database settings. This name is used to distinguish between them</param>
        /// <param name="filename">Name of the file that contains configurations to load</param>
        /// <returns>The database object to use</returns>
        public IDatabase Load(string filename, string name)
        {
            IDatabase result = null;

            if (File.Exists(filename))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);

                XmlElement section = null;

                for (int i = 0; i < doc.ChildNodes.Count; i++)
                {
                    XmlNode node = doc.ChildNodes[i];
                    if (node is XmlElement)
                    {
                        section = FindDatabaseSection(name, (XmlElement)node);
                        break;
                    }
                }

                if (section == null) DataConfigException.PublishNoDatabase(name);
                else result = ParseDatabase(section, name);
            }
            else Thn.Exceptions.FileNotFoundException.Publish(filename);

            return result;
        }
        #endregion
        #endregion

        #region Process Connection String
        /// <summary>
        /// Override this method to provide supports for connection string that is encrypted
        /// </summary>
        /// <param name="connection">the original value read from configuration file</param>
        /// <returns>the decrypted connection string</returns>
        protected virtual string ProcessConnectionString(string connection)
        {
            return connection;
        }
        #endregion

        #region Xml parsing
        #region Find Database Section
        XmlElement FindDatabaseSection(string name, XmlElement root)
        {
            XmlElement result = null;

            name = name.ToUpper();
            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                XmlNode node = root.ChildNodes[i];
                if ((node is XmlElement) && (node.Name.ToUpper() == "DATABASE"))
                {
                    if (name == string.Empty)
                    {
                        result = (XmlElement)node;
                        break;
                    }
                    else
                    {
                        bool match = false;

                        XmlElement el = (XmlElement)node;
                        
                        //find attribute NAME
                        for (int sub = 0; sub < el.ChildNodes.Count; sub++)
                        {
                            XmlNode subnode = el.ChildNodes[sub];
                            if ((subnode is XmlElement) && (subnode.Name.ToUpper() == "NAME"))
                            {
                                string databaseName = ((XmlElement)subnode).InnerText.ToUpper();
                                if (databaseName == name)
                                {
                                    match = true;
                                    break;
                                }
                            }
                        }

                        if (match)
                        {
                            result = el;
                            break;
                        }
                    }
                }
            }

            return result;
        }
        #endregion

        #region Parse Database
        IDatabase ParseDatabase(XmlElement section, string sectionName)
        {
            IDatabase result = null;
            string connection = "";

            for (int i = 0; i < section.ChildNodes.Count; i++)
            {
                XmlNode node = section.ChildNodes[i];

                if (node is XmlElement)
                {
                    XmlElement el = (XmlElement)node;
                    string elName = el.Name.ToUpper();

                    if (elName == "TYPE")
                    {
                        string dbType = el.InnerText.ToUpper();
                        if (dbType == "ACCESS") result = new Thn.Data.Database.Sql.AccessDatabase();
                        else if ((dbType == "SQL") || (dbType == "MSSQL")) result = new Thn.Data.Database.Sql.MsSqlDatabase();
                        else if (dbType == "XML") result = new Thn.Data.Database.Memory.XmlDatabase();
                        else if ((dbType == "MEMORY") || (dbType == "INMEMORY")) result = new Thn.Data.Database.Memory.InMemoryDatabase();
                    }
                    else if (elName == "CONNECTION")
                    {
                        connection = ProcessConnectionString(el.InnerText);
                    }
                }
            }

            if (result == null) DataConfigException.PublishNoType(sectionName);
            if ((connection == null) || (connection == string.Empty)) DataConfigException.PublishNoConnection(sectionName);

            if ((result != null) && (connection != null) && (connection != string.Empty))
            {
                result.Initialize(connection);
            }

            return result;
        }
        #endregion
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor
        /// </summary>
        public DataConfigurator()
        { }
        #endregion
    }
}
